package com.msg.xml;

import java.util.ArrayList;
import java.util.List;

/**
 * get data from the summary section and add the ticket summary information into the capacity summary
 * table
 * @author jeson9603
 *
 */
public class CapacitySummary_Manipulator extends Table_Manipulator {

	List<String> summaryData = null;
	
	protected CapacitySummary_Manipulator(Property prop) {
		super(prop);
		summaryData = new ArrayList<String>();
	}

	
	/**
	 * get the capacity data for each ticket levels from summary table, read the data of total $ and
	 * the summary data for each ticket level
	 */
	@Override
	protected String getSpecificData() {
		XMLhandler.findNodeByTag("***       SUMMARY");
		List<String> rawData = XMLhandler.getDataListByNode(XMLhandler.findNodeByTag("TOTAL CAPACITY"));
		summaryData.add(rawData.get(2));
		for(int i = 4; i < rawData.size(); i++) {
			if(rawData.get(i).compareTo("") == 0)
				break;
			summaryData.add(rawData.get(i));
		}
		return null;
	}

	/**
	 * update the data in the column ot Total_Amount_Sold in table event
	 */
	private void updateEvent() {
		DBRequest request = new DBRequest();
		String totalAmount = summaryData.get(0);
		request.resultCol.add("Total_Amount_Sold");
		request.resultColData.add(totalAmount.substring(1));
		request.entries.add("Event_Id");
		request.data.add(prop.getEVENT_ID());
		DBhandler.updateData("event", request);
	}
	
	/**
	 * update the data in the capacity summary table
	 */
	private void updateSummary() {
		String eventId = prop.getEVENT_ID();
		for(int i = 1; i < summaryData.size(); i++) {
			char ticketLv = (char)('A' + i - 1);
			String ticketLvId = TableUtility.getTicketLvID("" + ticketLv);
			DBRequest request = new DBRequest();
			request.resultCol.add("Number_Of_Seats");
			request.entries.add("Event_Id");
			request.entries.add("Ticket_Level_id");
			request.data.add(eventId);
			request.data.add(ticketLvId);
			
			//update the capacity summary table
			if(DBhandler.hasData("capacity_summary", request)) {
				request.resultColData.add(summaryData.get(i));
				DBhandler.updateData("capacity_summary", request);
			}
			
			//insert the data into capacity summary table
			else {
				DBRequest insertionRequest = new DBRequest();
				insertionRequest.entries.add("Event_Id");
				insertionRequest.entries.add("Ticket_Level_id");
				insertionRequest.entries.add("Number_Of_Seats");
				insertionRequest.data.add(eventId);
				insertionRequest.data.add(ticketLvId);
				insertionRequest.data.add(summaryData.get(i));
				DBhandler.insertData("capacity_summary", insertionRequest);
			}
		}
	}
	
	/**
	 * adding or updating the summary data for each ticket level and also changing the column
	 * Total_Amount_Sold in the event table
	 */
	@Override
	protected String update() {
		updateEvent();
		updateSummary();
		return null;
	}

	@Override
	protected void pushData(Object o) {
	}

}
